package framework.util.fileUpload.controller;

import framework.util.fileUpload.bo.SysFile;
import framework.util.fileUpload.bo.SysFileModule;
import framework.common.Common;
import framework.common.ResponseVo;
import framework.util.fileUpload.service.SysFileModuleService;
import framework.util.fileUpload.service.SysFileService;
import frameworkExt.util.controller.BaseControllerExt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用于处理文件上传相关业务
 *
 * @author 吴宇亮 2019年1月5日
 */
@RequestMapping("/Upload.do")
@Controller
public class UploadController extends BaseControllerExt {

    @Resource
    private SysFileModuleService sysFileModuleService;
    @Resource
    private SysFileService sysFileService;

    @RequestMapping(params = "method=upload")
    @ResponseBody
    public ResponseVo upload(HttpServletRequest request, MultipartFile file) {
        //文件模块id、uuid、是否为多文件上传
        String sysFileModuleLid = request.getParameter("sysFileModuleLid");
        String uuid = request.getParameter("uuid");
        if(StringUtils.isAnyBlank(sysFileModuleLid, uuid)){
            return sendFail("参数错误");
        }else if (file == null){
            return sendFail("文件为空，上传失败");
        }

        try {
            //上传文件
            SysFileModule sysFileModule = sysFileModuleService.get(Integer.valueOf(sysFileModuleLid));
            SysFile sysFile = sysFileService.upload(file, sysFileModule, uuid);
            sysFile.setIsTmp(Common.IS_YEW);
            sysFileService.add(sysFile);

            //防止文件名有特殊字符
            sysFileService.encodeURIComponent(sysFile);
            return sendSuccess(sysFile);
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }

    @RequestMapping(params = "method=deleteFiles")
    @ResponseBody
    public ResponseVo deleteFiles(HttpServletRequest request) {
        String sysFileLids = request.getParameter("sysFileLids");
        if(StringUtils.isAnyBlank(sysFileLids)){
            return sendFail("参数错误");
        }

        try {
            String[] sysFileLidArr = sysFileLids.split(",");
            sysFileService.deleteFiles(sysFileLidArr);

            return sendSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return sendError( e.getMessage());
        }
    }

}
